// reports.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')
Page({
  data: {
    reportList: [],
    statusList: ['全部', '待审核', '已通过', '已拒绝'],
    statusIndex: 0,
    page: 1,
    limit: 10,
    hasMore: true,
    loading: false,
    // 权限相关数据
    hasViewPermission: false,
    hasAuditPermission: false
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/reports/reports')) {
      return
    }
    
    this.checkPermissions()
    
    this.loadReports()
  },

  onShow() {
    this.refreshReports()
  },

  // 加载报工列表
  loadReports() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    const params = {
      page: this.data.page,
      limit: this.data.limit
    }
    
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusIndex - 1
    }
    
    api.getReports(params).then(res => {
      const newList = this.data.page === 1 ? res.data.list : [...this.data.reportList, ...res.data.list]
      
      // 格式化时间
      newList.forEach(item => {
        item.createtime_text = this.formatTime(item.createtime)
      })
      
      this.setData({
        reportList: newList,
        hasMore: res.data.list.length === this.data.limit,
        loading: false
      })
    }).catch(err => {
      this.setData({ loading: false })
      console.error('加载报工列表失败:', err)
    })
  },

  // 刷新报工列表
  refreshReports() {
    this.setData({
      page: 1,
      hasMore: true
    })
    this.loadReports()
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadReports()
    }
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: e.detail.value,
      page: 1,
      hasMore: true
    })
    this.loadReports()
  },

  // 跳转到报工详情
  goToReportDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/report-detail/report-detail?id=${id}`
    })
  },

  // 审核报工
  auditReport(e) {
    if (!this.hasPermission('report_manage', 'audit')) {
      wx.showToast({
        title: '您没有审核权限',
        icon: 'none'
      })
      return
    }
    
    const id = e.currentTarget.dataset.id
    const status = e.currentTarget.dataset.status
    e.stopPropagation()
    
    let title = status == '1' ? '确认通过该报工？' : '确认拒绝该报工？'
    
    wx.showModal({
      title: '确认操作',
      content: title,
      success: (res) => {
        if (res.confirm) {
          this.submitAudit(id, status)
        }
      }
    })
  },

  // 提交审核
  submitAudit(reportId, status) {
    const data = {
      report_id: reportId,
      status: status
    }
    
    if (status == '2') {
      // 拒绝时需要输入原因
      wx.showModal({
        title: '拒绝原因',
        editable: true,
        placeholderText: '请输入拒绝原因',
        success: (res) => {
          if (res.confirm) {
            data.audit_reason = res.content
            this.doSubmitAudit(data)
          }
        }
      })
    } else {
      this.doSubmitAudit(data)
    }
  },

  // 执行审核提交
  doSubmitAudit(data) {
    api.auditReport(data).then(res => {
      wx.showToast({
        title: '审核成功',
        icon: 'success'
      })
      this.refreshReports()
    }).catch(err => {
      console.error('审核失败:', err)
    })
  },

  // 格式化时间
  formatTime(timestamp) {
    const date = new Date(timestamp * 1000)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshReports()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadMore()
  },

  // 导航方法
  goToIndex() {
    console.log('点击了首页导航')
    wx.navigateTo({
      url: '/pages/index/index',
      success: () => {
        console.log('跳转到首页成功')
      },
      fail: (err) => {
        console.error('跳转到首页失败:', err)
      }
    })
  },

  goToAllocationManage() {
    console.log('点击了分工管理导航')
    wx.navigateTo({
      url: '/pages/allocation-manage/allocation-manage',
      success: () => {
        console.log('跳转到分工管理成功')
      },
      fail: (err) => {
        console.error('跳转到分工管理失败:', err)
      }
    })
  },

  // 格式化产品编号，去掉前缀
  formatItemNo(itemNo) {
    if (!itemNo) return ''
    // 去掉前缀 "ORD2025072591AE49-3+F-扪皮-"
    const prefix = 'ORD2025072591AE49-3+F-扪皮-'
    if (itemNo.startsWith(prefix)) {
      return itemNo.substring(prefix.length)
    }
    return itemNo
  },

  // 检查权限
  checkPermissions() {
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    
    if (!adminInfo || !adminInfo.id) {
      this.setData({
        hasViewPermission: false,
        hasAuditPermission: false
      });
      return;
    }
    
    // 超级管理员拥有所有权限
    if (adminInfo.id == 1 || adminInfo.id === 1 || adminInfo.id === '1') {
      this.setData({
        hasViewPermission: true,
        hasAuditPermission: true
      });
      return;
    }
    
    // 检查各项权限
    const hasViewPermission = permissionUtils.hasPermission(adminInfo.id, 'report_manage', 'view');
    const hasAuditPermission = permissionUtils.hasPermission(adminInfo.id, 'report_manage', 'audit');
    
    this.setData({
      hasViewPermission,
      hasAuditPermission
    });
    
    // 如果没有查看权限，显示提示并返回
    if (!hasViewPermission) {
      wx.showToast({
        title: '无权限访问此页面',
        icon: 'none',
        duration: 2000
      });
      
      setTimeout(() => {
        this.goBack();
      }, 2000);
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1,
      fail: () => {
        wx.switchTab({
          url: '/pages/index/index'
        });
      }
    });
  },

  // 检查是否有权限执行某个操作
  hasPermission(module, action) {
    // 从session中获取管理员信息
    const app = getApp();
    const adminInfo = app.globalData.adminInfo;
    if (!adminInfo || !adminInfo.id) {
      return false;
    }
    
    // 使用权限工具检查权限（基于管理组）
    return permissionUtils.hasPermission(adminInfo.id, module, action);
  }
}) 